/*
 * Copyright (c) 2025 粤港澳大湾区（广东）国创中心
 *
 * This file is a part of NctiCAEPre.
 *
 * NctiCAEPre is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 *
 */

#include "PreferenceSettings.h"
#include "UIOptionManager.h"
#include "UserInteractionManager.h"
#include "OptionsDlg.h"

#include "NctiQTPubFun.h"
#include "NctiWindowViewManager.h"
#include "NctiSystemParams.h"
#include "NctiDocument.h"
#include "NctiBaseModel.h"
#include "NctiDocElementPubFun.h"
#include "NctiWindowPlatform.h"

#include "NctiQtRightSideView.h"
#include "NctiBaseView.h"

namespace NCTI {

PreferenceSettings::PreferenceSettings(MainWindow* mainWindow)
    : MainWindowModule(mainWindow)
{
}

void PreferenceSettings::initialize()
{
    connect(m_mainWindow->Signals(), &MainWindowSignals::onOptions, this, &PreferenceSettings::openOptions);
}

void PreferenceSettings::initSelVisualMode()
{
    auto uiOptMgr = m_mainWindow->getUIOptionMgr();
    if (!uiOptMgr) {
        return;
    }

    auto selCheckBoxs    = uiOptMgr->getSelCheckBoxs();
    auto visualCheckBoxs = uiOptMgr->getVisualCheckBoxs();

    if (selCheckBoxs.empty() || visualCheckBoxs.empty()) {
        return;
    }

    NctiSystemParams* pSystemParams = NctiSystemParams::instance();
    bool body                       = true;
    bool face                       = true;
    bool edge                       = true;
    bool vertex                     = true;
    NctiQTPubFun::GetSel(m_mainWindow->getWindowPlatform(), body, face, edge, vertex);
    selCheckBoxs["select_body"]->setChecked(body);
    selCheckBoxs["select_face"]->setChecked(face);
    selCheckBoxs["select_edge"]->setChecked(edge);
    selCheckBoxs["select_vertex"]->setChecked(vertex);

    body   = pSystemParams->GetFaceState();
    face   = pSystemParams->GetFaceState();
    edge   = pSystemParams->GetEdgeState();
    vertex = pSystemParams->GetVertexState();
    NctiQTPubFun::GetVisualMode(m_mainWindow->getWindowPlatform(), face, edge, vertex);
    body = face && edge && vertex;
    visualCheckBoxs["visual_body"]->setChecked(body);
    visualCheckBoxs["visual_face"]->setChecked(face);
    visualCheckBoxs["visual_edge"]->setChecked(edge);
    visualCheckBoxs["visual_vertex"]->setChecked(vertex);
    if (body) {
        visualCheckBoxs["visual_face"]->setEnabled(false);
        visualCheckBoxs["visual_edge"]->setEnabled(false);
        visualCheckBoxs["visual_vertex"]->setEnabled(false);
    }
}

void PreferenceSettings::initDefaultColors()
{
    NctiSystemParams* pSystemParams = NctiSystemParams::instance();
    pSystemParams->SetTopColor(ParamsColor(5, 38, 79));
    pSystemParams->SetBottomColor(ParamsColor(81, 90, 146));
    pSystemParams->SetFaceColor(ParamsColor(145, 158, 186));
    pSystemParams->SetBackColor(ParamsColor(145, 158, 186));
    pSystemParams->SetLineColor(ParamsColor(0, 0, 0));
    pSystemParams->SetVertexColor(ParamsColor(248, 203, 22));
    pSystemParams->SetHighlightColor(ParamsColor(245, 128, 15));
}

void PreferenceSettings::handleThemeSelect(int index)
{
    if (index == 1) {
        //浅色主题
    }
    else if (index == 0) {
        //深色主题
    }
}

void PreferenceSettings::handleLanguageSelect(int index)
{
    if (index == 1) {
        //切换英文
    }
    else if (index == 0) {
        //切换中文
    }
}

void PreferenceSettings::handleBackgroundColorSetting(QColor topColor, QColor bottomColor)
{
    double r_top = static_cast<double>(topColor.red()) / 255.0;
    double g_top = static_cast<double>(topColor.green()) / 255.0;
    double b_top = static_cast<double>(topColor.blue()) / 255.0;

    double r_bottom = static_cast<double>(bottomColor.red()) / 255.0;
    double g_bottom = static_cast<double>(bottomColor.green()) / 255.0;
    double b_bottom = static_cast<double>(bottomColor.blue()) / 255.0;

    NctiWindowViewManager* pViewManager = m_mainWindow->getWindowPlatform()->GetCurrentViewManager();
    if (pViewManager) {
        NctiBaseView* pBaseView = pViewManager->GetMainBaseView();
        //背景
        pBaseView->GetScene()->SetBackGround(true);
        pBaseView->GetScene()->SetWindowColor({ r_top, g_top, b_top });
        pBaseView->GetScene()->SetWindowContrastColor({ r_bottom, g_bottom, b_bottom });
        pBaseView->Update();
    }
}

void PreferenceSettings::handleModelColorSetting(QColor faceColor, QColor edgeColor, QColor vertexColor)
{
    NctiWindowViewManager* pViewManager = m_mainWindow->getWindowPlatform()->GetCurrentViewManager();
    if (pViewManager) {
        NctiBaseView* pBaseView         = pViewManager->GetMainBaseView();
        NctiRenderSceneItem* pSceneItem = pBaseView->GetScene();
        //模型颜色，点、线、面
        pSceneItem->GetMaterialMappingControl()->SetFaceColor(RGBAColor(faceColor.name().toStdString()));
        pSceneItem->GetMaterialMappingControl()->SetLineColor(RGBAColor(edgeColor.name().toStdString()));
        pSceneItem->GetMaterialMappingControl()->SetVertexColor(RGBAColor(vertexColor.name().toStdString()));
        pBaseView->Update();
    }
}

//草图颜色，暂且不动
void PreferenceSettings::handleSketchColorSetting(QColor lineSegmentColor,
                                                  QColor dimensionLineColor,
                                                  QColor gridLineColor)
{
}

void PreferenceSettings::handleObjectDisplayMode(bool faceState, bool edgeState, bool vertexState)
{
    NctiQTPubFun::SetVisualMode(m_mainWindow->getWindowPlatform(), faceState, edgeState, vertexState);
    initSelVisualMode();
}

void PreferenceSettings::handleConsole(bool consoleState)
{
    m_mainWindow->getUserInteractionMgr()->showCommandConsole(consoleState);
}

void PreferenceSettings::handleScriptEditor(bool scriptEditorState)
{
    NctiQtRightSideView* rightSideView = m_mainWindow->getUserInteractionMgr()->getRightSideView();
    if (!rightSideView) {
        return;
    }

    if (scriptEditorState) {
        rightSideView->changeCurrentView(NctiQtRightSideView::ViewEditor);
    }
    else {
        rightSideView->hideScriptEditor();
    }
}

void PreferenceSettings::handleBackups(bool openState, const std::string& path, int time)
{
}

void PreferenceSettings::LoadingUIBasedOnJson()
{
    NctiSystemParams* pSystemParams = NctiSystemParams::instance();
    
    //控制台
    handleConsole(pSystemParams->GetConsole());
    
    //脚本编辑器
    handleScriptEditor(pSystemParams->GetScriptEditor());

    //备份
    //备份开启或关闭
    if (pSystemParams->GetAutoSaveValid()) {
        if (pSystemParams->GetAutoSaveTime() > 0 && !pSystemParams->GetAutoSaveFolder().empty()) {
            handleBackups(pSystemParams->GetAutoSaveValid(),
                          pSystemParams->GetAutoSaveFolder(),
                          pSystemParams->GetAutoSaveTime());
        }
    }

    NctiDocument* i_pDocument = NctiQTPubFun::GetCurrentViewDocment(m_mainWindow->getWindowPlatform());
    if (i_pDocument && i_pDocument->GetBaseModel()) {
        auto view = i_pDocument->GetBaseModel()->GetActiveBaseView();
        if (view) { 
            NctiDocElementPubFun::InitDisplay(view);
        }
    }
}

void PreferenceSettings::openOptions()
{
    OptionsDlg dlg(m_mainWindow);
    connect(&dlg, &OptionsDlg::savePushButtonClicked, this, &PreferenceSettings::LoadingUIBasedOnJson);

    NctiWindowPlatform* platform = m_mainWindow->getWindowPlatform();
    if (NctiQTPubFun::GetCurrentViewDocment(platform)) {
        //对象显示模式同步
        bool face = false;
        bool edge = false;
        bool vertex = false;
        NctiQTPubFun::GetVisualMode(platform, face, edge, vertex);
        dlg.setObjectDisplayMode(face, edge, vertex);
        dlg.updateDisplayModeIcon();

        //控制台，脚本编辑器显示同步
        //dlg.setConsoleState(m_mainWindow->getUserInteractionMgr()->getConsoleState());
        //dlg.setScriptEditorState(m_mainWindow->getUserInteractionMgr()->getScriptEditorState());
    }
    dlg.exec();
}

} // namespace NCTI